import React, { useState } from "react";
import MyNavBar from "../../../components/MyNavBar";
import { SearchBar } from "antd-mobile";
import API from "../../../utils/api";
import NoHouse from "../../../components/NoHouse";
import { getCity } from "../../../utils/city";
import styles from "./index.module.css";

export default function Search(props) {
  let cityId = getCity().value;
  let timerId = null;

  const [tipList, settipList] = useState([]);
  const [searchText, setsearchText] = useState("");
  // 渲染搜素结果列表
  const renderTips = () => {
    if (tipList.length === 0) {
      return <NoHouse>这里空空如也，换个词试试吧~</NoHouse>;
    }
    return tipList.map((item) => (
      <div
        key={item.community}
        className={styles.tip}
        onClick={() => onTipClick(item)}
      >
        {item.communityName}
      </div>
    ));
  };

  const onTipClick = (item) => {
    props.history.replace("/rent/add", {
      name: item.communityName,
      id: item.community,
    });
  };

  const handleSearchText = (value) => {
    setsearchText(value);
    if (!value) {
      // 如果没有输入值
      settipList([]);
    } else {
      /* 避免重发送请求 */
      // 清除上一次定时器
      clearTimeout(timerId);

      timerId = setTimeout(async () => {
        // 获取小区数据
        const res = await API.get("/area/community", {
          params: {
            name: value,
            id: cityId,
          },
        });
        settipList(res.data.body);
      }, 500);
    }
  };
  return (
    <div className={styles.root}>
      <MyNavBar>搜索</MyNavBar>
      <SearchBar
        value={searchText}
        placeholder="请输入小区名称"
        showCancelButton
        onChange={handleSearchText}
      />
      <div className={styles.tips}>{renderTips()}</div>
    </div>
  );
}
